from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
# from hwx_function import *
import os
import time
import requests
from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
import json


def Describe_SubDomain_Records(client, record_type, subdomain):
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')

    request.set_Type(record_type)
    request.set_SubDomain(subdomain)

    response = client.do_action_with_exception(request)
    response = str(response, encoding='utf-8')
    relsult = json.loads(response)
    return relsult


def update_record(client, priority, ttl, record_type, value, rr, record_id):
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')

    request.set_Priority(priority)
    request.set_TTL(ttl)
    request.set_Value(value)
    request.set_Type(record_type)
    request.set_RR(rr)
    request.set_RecordId(record_id)

    response = client.do_action_with_exception(request)
    response = str(response, encoding='utf-8')
    return response


if __name__ == '__main__':
    while True:

        ipv6 = None
        try:
            client = AcsClient('LTAI5t8KtmkACeMgfWpW4qE8', '5NubvhBgMaVJEaQLTgWEUQWM24yD5n')
            response = requests.get("http://[2402:4e00:1013:e500:0:9671:f018:4947]/")
            # print(response.text)
            if response.status_code == 200:
                ipv6 = response.text
            else:
                print(f"ERROR:接口获取失败{response.status_code}")
                continue
        except OSError:
            print("获取IPv6时发生了一个错误，可能导致的原因有：1.ipv6接口错误；2.您的网络不支持ipv6；3.检查网络是否已经连接")
            time.sleep(10)
            continue
        print(f"当前本机：{ipv6}")

        with open("ipv6", 'r') as f:
            old_ip = f.read()

        if old_ip != ipv6:
            des_relsult = Describe_SubDomain_Records(client, "AAAA", "www.chengsh.xyz")
            # print(des_relsult)
            record_id = des_relsult["DomainRecords"]["Record"][0]["RecordId"]
            # record_ip = des_relsult["DomainRecords"]["Record"][0]["Value"]
            # print(record_id)
            result = update_record(client, "5", "600", "AAAA", ipv6, "www", record_id)
            # 校验是否更新成功
            des_relsult = Describe_SubDomain_Records(client, "AAAA", "www.chengsh.xyz")
            record_ip = des_relsult["DomainRecords"]["Record"][0]["Value"]
            if record_ip == ipv6:
                print(f"域名解析更新成功：{ipv6}")
                with open("ipv6", 'w') as f:
                    f.write(ipv6)
                time.sleep(5)
            else:
                print("域名解析更新错误")
                continue
        else:
            print("ipv6没有变化")
            time.sleep(30)